package com.atguigu.ssyx.search.receiver;

import com.atguigu.ssyx.rabbitmq.constant.MqConstant;
import com.atguigu.ssyx.search.service.SkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 监听商品上下架服务发送的消息
 */
@Component
public class SkuReceiver {

    @Resource
    private SkuService skuService;

    /**
     * 商品上架
     * @param skuId
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConstant.QUEUE_GOODS_UPPER, durable = "true"),
            exchange = @Exchange(value = MqConstant.EXCHANGE_GOODS_DIRECT),
            key = {MqConstant.ROUTING_GOODS_UPPER}))
    public void upperSku(Long skuId, Message message, Channel channel) throws IOException {
        if (skuId != null) {
            // 商品上架
            skuService.upperSku(skuId);
        }
        /*
         * 手动确认消息
         * 1. 参数1: 手动确认消息的编号：getDeliveryTag
         * 2. 参数2: 是否开启多个消息同时确认
         */
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    /**
     * 商品下架
     * @param skuId
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConstant.QUEUE_GOODS_LOWER, durable = "true"),
            exchange = @Exchange(value = MqConstant.EXCHANGE_GOODS_DIRECT),
            key = {MqConstant.ROUTING_GOODS_LOWER}))
    public void lowerSku(Long skuId, Message message, Channel channel) throws IOException {
        if (skuId != null) {
            // 商品下架
            skuService.lowerSku(skuId);
        }
        /*
         * 手动确认消息
         * 1. 参数1: 手动确认消息的编号：getDeliveryTag
         * 2. 参数2: 是否开启多个消息同时确认
         */
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
